package com.whl.sm.service.impl.repair;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.whl.sm.common.result.Result;
import com.whl.sm.mapper.repair.RepairTaskMapper;
import com.whl.sm.model.repair.RepairApply;
import com.whl.sm.model.repair.RepairTask;
import com.whl.sm.model.system.OrgUserInfo;
import com.whl.sm.service.repair.RepairApplyService;
import com.whl.sm.service.repair.RepairTaskService;
import com.whl.sm.service.system.OrgUserInfoService;
import com.whl.sm.service.system.OrgUserService;
import com.whl.sm.sysEnum.CommonEnum;
import com.whl.sm.vo.WxRepairApplyTaskVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author wuhaolun
 * @since 2021-11-28
 */
@Slf4j
@Service
public class RepairTaskServiceImpl extends ServiceImpl<RepairTaskMapper, RepairTask> implements RepairTaskService {

    @Autowired
    private OrgUserService orgUserService;

    @Autowired
    private OrgUserInfoService orgUserInfoService;

    @Autowired
    private RepairApplyService repairApplyService;

    @Override
    public Result update(RepairTask repairTask) {
        try{
            if (Objects.isNull(repairTask.getId())){
                getBaseMapper().insert(repairTask);
            }else{
                getBaseMapper().updateById(repairTask);
            }
        }catch (Exception e){
            log.error("报修工单更新异常:"+e.getMessage());
            return Result.fail();
        }
        return Result.ok();
    }

    @Override
    public Result getNotFinByCurrent(Page page) {
        String userId = orgUserService.getCurrentUserId();
        //userId = "a5b2ecb614b5a242444dd6b2f0985c6b";
        List<Object> linkApplyList = new ArrayList<>();
        Page<Object> listPage;
        listPage = getBaseMapper().selectPage(page,new QueryWrapper<RepairTask>()
                .isNull("complete_time")
                .eq("staff_id",userId)
                .ne("is_del",1)
                .orderByDesc("update_time")
        );
        if (listPage.getRecords().size()>0){
            linkApplyList = listPage.getRecords().stream().map(obj->{
                RepairTask item = (RepairTask) obj;
                RepairApply linkApply = repairApplyService.getById(item.getLinkApplyId());
                OrgUserInfo applicant = orgUserInfoService.getByUserId(linkApply.getApplicant());
                linkApply.setApplicantName(applicant.getUserName());
                return linkApply;
            }).collect(Collectors.toList());
         }
        listPage.setRecords(linkApplyList);
        return Result.ok(listPage);
    }

    @Override
    public Result getFinByCurrent(Page page) {
        String userId = orgUserService.getCurrentUserId();
        //userId = "a5b2ecb614b5a242444dd6b2f0985c6b";
        List<Object> taskInfoVos = new ArrayList<>();
        Page<Object> listPage;
        listPage = getBaseMapper().selectPage(page,new QueryWrapper<RepairTask>()
                .eq("staff_id",userId)
                .ne("is_del",1)
                .orderByDesc("update_time")
                .isNotNull("complete_time")
        );
        if (listPage.getRecords().size()>0){
            taskInfoVos = listPage.getRecords().stream().map(obj->{
                RepairTask item = (RepairTask) obj;
                RepairApply linkApply = repairApplyService.getById(item.getLinkApplyId());
                OrgUserInfo applicant = orgUserInfoService.getByUserId(linkApply.getApplicant());
                linkApply.setApplicantName(applicant.getUserName());
                return new WxRepairApplyTaskVo(linkApply,item);
            }).collect(Collectors.toList());
        }
        listPage.setRecords(taskInfoVos);
        return Result.ok(listPage);
    }

    @Override
    public Result confirmTask(String id,String feedBack) {
        try{
            RepairTask dataItem = getBaseMapper().selectById(id);
            dataItem.setRepairFeedback(feedBack);
            Result updateResult = update(dataItem);
            if (!updateResult.isOk()){
                return updateResult;
            }
            RepairApply linkApply = repairApplyService.getById(dataItem.getLinkApplyId());
            linkApply.setStep(CommonEnum.RepairStatus.REPAIRING.getStep());
            Result updateApply =  repairApplyService.update(linkApply);
            if (!updateApply.isOk()){
                return updateApply;
            }
        }catch (Exception e){
            log.error("维修工单确认失败==========>"+e.getMessage());
            return Result.fail();
        }
        return Result.ok();
    }

    @Override
    public Result completeTask(String id) {
        try {
            RepairTask dataItem = getBaseMapper().selectById(id);
            dataItem.setCompleteTime(new Date());
            dataItem.setRepairFeedback("维修完成");
            Result upResult = update(dataItem);
            if (!upResult.isOk()){
                return upResult;
            }
            RepairApply linkApply = repairApplyService.getById(dataItem.getLinkApplyId());
            linkApply.setStep(CommonEnum.RepairStatus.COMPLETE.getStep());
            linkApply.setCompleteTime(new Date());
            Result updateApply =  repairApplyService.update(linkApply);
            if (!updateApply.isOk()){
                return updateApply;
            }
        }catch (Exception e){
            log.error("维修工单完成失败==========>"+e.getMessage());
            return Result.fail();
        }
        return Result.ok();
    }

    @Override
    public Result appraise(String id, Double source, String appraise) {
        try {
            RepairTask task = getBaseMapper().selectById(id);
            RepairApply linkApply = repairApplyService.getById(task.getLinkApplyId());
            task.setSource(source);
            task.setAppraise(appraise);
            Result updateTask = update(task);
            if (!updateTask.isOk()){
                return updateTask;
            }
            linkApply.setStep(CommonEnum.RepairStatus.APPRAISE.getStep());
            Result updateApply =  repairApplyService.update(linkApply);
            if (!updateApply.isOk()){
                return updateApply;
            }
        }catch (Exception e){
            log.error("工单评价失败==========>"+e.getMessage());
            return Result.fail();
        }
        return Result.ok();
    }


}
